import ColorUISdk from '../../mp-sdk/index'

// 定义接口类型
interface RecordItem {
  id: string;
  image_url: string;
  building_name: string;
  building_description: string;
  saved: boolean;
  created_at: string;
}

interface RecordsResponse {
  code: number;
  data?: {
    records: RecordItem[];
    total: number;
    page: number;
    limit: number;
  };
  msg?: string;
}

const sdk = new ColorUISdk({
  env: 'dev',
  version: '1.0.0',
  api: {
    dev: { 
      url: 'http://192.168.134.31:5000'
    }
  }
})

Page({
  data: {
    records: [] as RecordItem[],
    currentPage: 1,
    totalRecords: 0,
    hasMore: true,
    isLoading: false,
    showSavedOnly: false,
    activeTab: 0 // 0: 全部, 1: 已保存
  },

  onLoad() {
    // 检查登录状态
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      wx.navigateTo({ url: '/pages/login/login' })
      return
    }
    
    this.loadRecords()
  },

  // 切换标签
  onTabChange(e: any) {
    const tabIndex = e.detail.index
    this.setData({
      activeTab: tabIndex,
      showSavedOnly: tabIndex === 1,
      currentPage: 1,
      records: [],
      hasMore: true
    }, () => {
      this.loadRecords()
    })
  },

  // 加载记录 - 修复API路径
  async loadRecords() {
    if (this.data.isLoading || !this.data.hasMore) return
    
    this.setData({ isLoading: true })
    
    const token = wx.getStorageSync('token')
    const { currentPage, showSavedOnly } = this.data
    
    try {
      const savedParam = showSavedOnly ? '&saved_only=true' : ''
      // 修复API路径：使用正确的识别记录API
      const res = await sdk.request({
        url: `/api/records?page=${currentPage}&limit=10${savedParam}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      }) as RecordsResponse
      
      if (res.code === 0 && res.data) {
        const { records, total, page: currentPage } = res.data
        this.setData({
          records: currentPage === 1 ? records : [...this.data.records, ...records],
          totalRecords: total,
          currentPage,
          hasMore: currentPage * 10 < total
        })
      } else {
        wx.showToast({
          title: res.msg || '获取记录失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取记录失败:', error)
      wx.showToast({
        title: '获取记录失败',
        icon: 'none'
      })
    } finally {
      this.setData({ isLoading: false })
    }
  },

  // 加载更多
  loadMore() {
    if (!this.data.hasMore || this.data.isLoading) return
    this.setData({
      currentPage: this.data.currentPage + 1
    }, () => {
      this.loadRecords()
    })
  },

  // 切换保存状态 - 修复API路径
  async toggleSaveRecord(e: any) {
    const { id, saved } = e.currentTarget.dataset
    const token = wx.getStorageSync('token')
    
    if (!token || !id) return
    
    try {
      wx.showLoading({ title: saved ? '取消保存中...' : '保存中...' })
      
      // 修复API路径：使用正确的保存/取消保存API
      const url = saved 
        ? `/api/records/unsave/${id}`
        : `/api/records/save/${id}`
      
      const res = await sdk.request({
        url,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      wx.hideLoading()
      
      if (res.code === 0) {
        wx.showToast({
          title: saved ? '取消保存成功' : '保存成功',
          icon: 'success'
        })
        
        // 更新本地记录状态
        const updatedRecords = this.data.records.map(record => 
          record.id === id ? { ...record, saved: !saved } : record
        )
        
        this.setData({
          records: updatedRecords
        })
      } else {
        wx.showToast({
          title: res.msg || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('操作记录失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 查看记录详情
  viewRecordDetail(e: any) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/record-detail/record-detail?id=${id}`
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      currentPage: 1,
      hasMore: true
    }, () => {
      this.loadRecords().then(() => {
        wx.stopPullDownRefresh()
      })
    })
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMore()
  }
})